#include "RequestCP.hpp"

using namespace BFT::messages;

RequestCP::RequestCP(uint32_t _seqNo, uint32_t _sender)
	: MacArrayMessage::MacArrayMessage(REQUEST_CP, computeSize(), _sender, BFT::Parameters::getExecutionCount())
{
	seqNo = _seqNo;
	
	int bytes_size;
	boost::shared_ptr<char> bytes = getBytes(bytes_size);
	
	int offset = getOffset();
	
	//wtire the sequence number
	
	*(uint32_t*)(bytes.get()+offset) = htonl(seqNo);
}

RequestCP::RequestCP(boost::shared_ptr<char> _bytes, int _bytes_size)
	: MacArrayMessage::MacArrayMessage(_bytes, _bytes_size)
{
	if (getTag() != REQUEST_CP)
	{
		fprintf(stderr, "trying to build a RequestCP from invalid bytes. expectyed tag: %d, actual tag: %d\n",RELEASE_CP, getTag());
		exit(105);
	}
	
	unsigned int offset = getOffset();
	
	//read the sequence number
	seqNo = ntohl( *(uint32_t*)_bytes.get()+offset );
	offset += SEQUENCE_NUMBER_SIZE;
	
	if (offset != _bytes_size - getAuthenticationSize())
	{
		fprintf(stderr, "trying to build a RequestCP from invalid bytes\n");
		exit(106);
	}	
}

uint32_t RequestCP::computeSize()
{
	return SEQUENCE_NUMBER_SIZE;
}

void RequestCP::printInfo()
{
	fprintf(stdout, "RequestCP information...\n");
	fprintf(stdout, "seqNo: %d\n", seqNo);
}
